package cn.com.generaldata.os.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.lang.Streams;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cn.com.generaldata.os.common.Excels;
import cn.com.generaldata.os.service.impl.IndicatorStatService;
import cn.com.generaldata.os.service.intf.IndicatorServiceInterface;
import cn.com.generaldata.os.vo.IndicatorStatQueryVO;
import cn.com.generaldata.os.vo.IndicatorStatResult;

import com.google.common.net.HttpHeaders;

/**
 * 指标汇总Controller.
 */
public class IndicatorStatController extends MultiActionController {

	private IndicatorStatService indicatorStatService;
	private IndicatorServiceInterface indicatorService;

	public void setIndicatorService(IndicatorServiceInterface indicatorService) {
		this.indicatorService = indicatorService;
	}

	public void export(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		String encodedfileName = new String("指标汇总结果.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		try {
			List<IndicatorStatResult> results = indicatorStatService.indicatorStat(command);
			Excels.exportObj2Excel(IndicatorStatResult.class, results, out);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void account(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {

		int year = command.getYear();
		int yearEnd = command.getYearTime();

		String fileName = year + "—" + yearEnd + "指标核算结果.xls";

		response.setContentType("multipart/form-data");
		String userAgent = request.getHeader("User-Agent");
		byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
		fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
		response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));

		OutputStream out = response.getOutputStream();
		try {

			indicatorService.exportAccountExcel(out, year, yearEnd);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void select(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		File file = new File(properties.getProperty("fileUploadPath").trim() + command.getProvinceId()); // 路径是存文件的路径
		String encodedfileName = new String("指标统计结果.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		FileInputStream fin = new FileInputStream(file);
		byte data[] = new byte[1024];
		int len;
		try {
			while ((len = fin.read(data)) > -1) {
				out.write(data);
			}
			fin.close();
			out.close();
			out.flush();
		} finally {
			Streams.safeClose(out);
			file.delete();
		}
	}

	public void downExcel(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		File file = new File(properties.getProperty("excelDownPath").trim() + command.getProvinceId()); // 路径是存文件的路径
		String encodedfileName = new String(command.getProvinceId().getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		FileInputStream fin = new FileInputStream(file);
		byte data[] = new byte[1024];
		int len;
		try {
			while ((len = fin.read(data)) > -1) {
				out.write(data);
			}
			fin.close();
			out.close();
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void downUser(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		InputStream resourceAsStream = getClass().getResourceAsStream("/user-handle.doc");
		String encodedfileName = new String("用户手册.doc".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		byte data[] = new byte[1024];
		int len;
		try {
			while ((len = resourceAsStream.read(data)) > -1) {
				out.write(data);
			}
			resourceAsStream.close();
			out.close();
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void indicatorTemple(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		String type = command.getProvinceId();
		String industry = command.getCityId();
		String encodedfileName = new String("指标录入模板.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		try {
			indicatorService.downIndicatorTemple(out, type, industry);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void fileTemple(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		String path = command.getProvinceId();
		String name = command.getCityId();
		String encodedfileName = new String(name.getBytes("ISO8859-1"), "utf-8");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			System.out.print(ex);
		}
		File file = new File(properties.getProperty("fileUploadPath").trim() + path); // 路径是存文件的路径
		FileInputStream stream = new FileInputStream(file);
		Streams.writeAndClose(out, stream);
	}

	public void gdpCodeTemple(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		String year = command.getProvinceId();
		Integer type = command.getYearTime();
		if (type == 1) {
			String encodedfileName = new String("国民经济代码模板.xls".getBytes(), "ISO8859-1");
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
			OutputStream out = response.getOutputStream();
			try {
				indicatorService.downGDPCodeTemple(out, year);
				out.flush();
			} finally {
				Streams.safeClose(out);
			}
		} else if (type == 2) {
			String encodedfileName = new String("直接消耗系数模板.xls".getBytes(), "ISO8859-1");
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
			OutputStream out = response.getOutputStream();
			try {
				indicatorService.downCoefficientTemple(out, year);
				out.flush();
			} finally {
				Streams.safeClose(out);
			}
		} else if (type == 3) {
			String encodedfileName = new String("基本流量表模板.xls".getBytes(), "ISO8859-1");
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
			OutputStream out = response.getOutputStream();
			try {
				indicatorService.downBasicFlowTemple(out, year);
				out.flush();
			} finally {
				Streams.safeClose(out);
			}
		}
	}

	//下载企业模板
	public void enterpriseTemple(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String encodedfileName = new String("企业导入模板.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		try {
			indicatorService.downEnterpriseTemple(out);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void unitProTemple(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String encodedfileName = new String("用海情况导入模板.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		try {
			indicatorService.unitProTemple(out);
			out.flush();
		} finally {
			Streams.safeClose(out);
		}
	}

	public void errorFile(HttpServletRequest request, HttpServletResponse response, IndicatorStatQueryVO command)
			throws Exception {
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			logger.error("加载配置文件出错", ex);
		}
		File file = new File(properties.getProperty("fileUploadPath").trim() + command.getProvinceId()); // 路径是存文件的路径
		String encodedfileName = new String("录入信息异常.xls".getBytes(), "ISO8859-1");
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
		OutputStream out = response.getOutputStream();
		FileInputStream fin = new FileInputStream(file);
		byte data[] = new byte[1024];
		int len;
		try {
			while ((len = fin.read(data)) > -1) {
				out.write(data);
			}
			fin.close();
			out.close();
			out.flush();
		} finally {
			Streams.safeClose(out);
			file.delete();
		}
	}

	public void setIndicatorStatService(IndicatorStatService indicatorStatService) {
		this.indicatorStatService = indicatorStatService;
	}

	public String findServerPath() {
		String classPath = this.getClass().getClassLoader().getResource("/").getPath();
		try {
			classPath = URLDecoder.decode(classPath, "gb2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String[] strPath = classPath.split("/");
		String path = "";
		for (int i = 0; i < strPath.length; i++) {
			if (i > 0 && i <= 3) {
				path = path + strPath[i] + "/";
			}
		}
		return path;
	}

}
